package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Utils.DateUtils;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author 林道样
 * @date 2020-03-05 15:20
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetmealDao setmealDao;

    //体检预约
    public Result order(Map map) throws Exception {
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findOrderSetting(date);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //判断是否在重复预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            Integer memberId = member.getId();//会员id
            Integer setmealId = Integer.parseInt((String) map.get("setmealId"));//套餐id
            Order order = new Order(memberId, date, setmealId);
            List<Order> orderList = orderDao.findByCondition(order);
            if (orderList != null && orderList.size() > 0) {
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }

        if (member == null) {
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //保存预约信息
        Order order = new Order(member.getId(), date, (String) map.get("orderType"), Order.ORDERSTATUS_NO, Integer.parseInt((String) map.get("setmealId")));
        orderDao.add(order);

        //更新已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editNumberByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    //根据id查询预约详细信息（包括会员姓名、套餐名称、预约基本信息）
    public Map findById(Integer id) {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            Date orderDate = (Date) map.get("orderDate");
            try {
                map.put("orderDate", DateUtils.parseDate2String(orderDate));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    @Override
    public PageResult pageQuery(Map map) throws Exception {
        Integer currentPage = (Integer) map.get("currentPage");
        Integer pageSize = (Integer) map.get("pageSize");
        List<String> date = (List<String>) map.get("date");
        if (date != null && date.size() > 0) {
            String[] s1 = date.get(0).split("T");
            String[] s2 = date.get(1).split("T");
            map.remove("date");
            String[] dates = {s1[0], s2[0]};
            map.put("date", dates);
        }
        PageHelper.startPage(currentPage, pageSize);
        Page<Map<String, Object>> orders = orderDao.findAllByCondition(map);
        for (Map<String, Object> order : orders) {
            Integer setmeal_id = (Integer) order.get("setmeal_id");
            String setmealName = orderDao.findSetmealById(setmeal_id);
            order.put("setmealName", setmealName);
        }
        long total = orders.getTotal();
        List<Map<String, Object>> result = orders.getResult();
        return new PageResult(total, result);
    }

    @Override
    public Result add(Map map, Integer setmealIds) throws Exception {
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findOrderSetting(date);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //判断是否在重复预约
        String telephone = (String) map.get("phoneNumber");
        System.out.println(telephone);
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            String memberName = member.getName();
            String setmealName = (String) map.get("setmealName");
            Map omap = new HashMap<String, Object>();
            omap.put("setmealName", setmealName);
            omap.put("date", date);
            omap.put("memberName", memberName);
            Map<String, Object> order = orderDao.findOrderByCondition(omap);
            if (order != null) {
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }

        if (member == null) {
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //保存预约信息
        Order order = new Order(member.getId(),
                date,
                "电话预约",
                Order.ORDERSTATUS_NO,
                setmealIds);
        orderDao.add2(order);

        //更新已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editNumberByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }


    @Override
    public void edit(Map map, Integer orderId) {
        orderDao.edit(map);
        String name = (String) map.get("name");
        Order order = orderDao.findById(orderId);
        Integer memberId = order.getMember_id();
        Member member = memberDao.findById(memberId);
        member.setName(name);
        memberDao.edit(member);
    }

    @Override
    public void delete(Integer id) {
        orderDao.delete(id);
    }

    @Override
    public void changeOrderStatus(Integer id) {
        Order order = orderDao.findById(id);
        String orderStatus = order.getOrderStatus();
        if ("未到诊".equals(orderStatus)) {
            orderStatus = "已完成";
        } else {
            orderStatus = "未到诊";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("orderStatus", orderStatus);
        orderDao.changeOrderStatus(map);
    }


    @Override
    public Map<String, Object> findOrderById(Integer id) throws Exception {
        Map map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        Order order = orderDao.findById(id);
        Member member = memberDao.findById(order.getMember_id());
        Map ordermap = new HashMap<>();
        ordermap.put("date", DateUtils.parseDate2String(order.getOrderDate()));
        ordermap.put("name", member.getName());
        ordermap.put("orderType", order.getOrderType());
        ordermap.put("orderStatus", order.getOrderStatus());
        list.add(order.getSetmeal_id());
        map.put("ordermap", ordermap);
        map.put("setmealIds", list);
        return map;
    }

}
